package cn.wolfcode.luowowo.website.web.util;

import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
    public static void addCookie(String key, String value, int time, HttpServletResponse response) {
        Cookie c = new Cookie(key, value);
        //设置cookie的存活时间
        c.setMaxAge(time);
        c.setPath("/");//cookie共享路径
        response.addCookie(c);
    }

    public static String getToken(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        String token = null;
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                    //延长时间token 在cookie的时间
                    CookieUtil.addCookie("token", token, RedisKeys.TOKEN_USER_INFO.getTime().intValue(), response);
                    break;
                }
            }
        }
        return token;
    }
}
